//
//  YZMWaterWaveView.m
//  YZMicroStock
//
//  Created by wangminhong on 16/3/23.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMWaterWaveView.h"
#import "YZMAppStyle.h"

@implementation YZMWaterWaveView{
    
    float _currentLinePointY;
    
    float a;
    BOOL jia;
}

- (id)initWithFrame:(CGRect)frame{
    
    self = [super initWithFrame:frame];
    if (self) {
        
        self.backgroundColor = [UIColor clearColor];
        self.userInteractionEnabled = NO;
        
        a = 1.5;
        jia = NO;
        self.darkPosition = 0;
        self.lightPosition = 30;
        self.darkColor = [UIColor colorWithRed:245/255.0 green:71/255.0 blue:55/255.0 alpha:1.0];
        self.lightColor = [UIColor colorWithRed: 243/255.0 green:55/255.0 blue:55/255.0 alpha: 0.5];
        
        _currentLinePointY = frame.size.height/2+20;
        
        [NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(animateWave) userInfo:nil repeats:YES];
    }
    
    return self;
}


-(void)animateWave
{
    if (jia) {
        a += 0.01;
    }else{
        a -= 0.01;
    }
    
    
    if (a <= 1) {
        jia = YES;
    }
    
    if (a >= 1.5) {
        jia = NO;
    }
    
    self.lightPosition += 1;
    self.darkPosition += 1;
    
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect
{
    
    for (int i= 0; i<2; i++) {
        
        UIColor *color = (i==0?self.darkColor:self.lightColor);
        NSInteger position = (i==0?self.darkPosition:self.lightPosition);
        
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGMutablePathRef path = CGPathCreateMutable();
        
        //画水
        CGContextSetLineWidth(context, 1);
        CGContextSetFillColorWithColor(context, [color CGColor]);
        
        float y=_currentLinePointY;
        CGPathMoveToPoint(path, NULL, 0, y);
        for(int x=0;x<=self.frame.size.width;x++){
            y= a * sin( 2*M_PI*x/self.frame.size.width + 2* position*M_PI/90 ) *3 + _currentLinePointY;
            CGPathAddLineToPoint(path, nil, x, y);
        }
        
        CGPathAddLineToPoint(path, nil, self.frame.size.width, rect.size.height);
        CGPathAddLineToPoint(path, nil, 0, rect.size.height);
        CGPathAddLineToPoint(path, nil, 0, _currentLinePointY);
        
        CGContextAddPath(context, path);
        CGContextFillPath(context);
        CGContextDrawPath(context, kCGPathStroke);
        CGPathRelease(path);
    }
}

@end
